package com.yt.sys.api.client;

import com.yt.common.constant.Result;
import com.yt.sys.common.config.AlipayConfig;
import com.yt.sys.models.service.IPaymentOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 统一账单结算接口控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/bill-settlement")
@Api(value = "BillUnifiedSettlementController", tags = "统一账单结算接口")
public class BillUnifiedSettlementController {

    @Resource
    private AlipayConfig alipayConfig;

    // 注入账单服务
    @DubboReference
    private com.yt.phone.models.service.IBillService billService;
    
    // 注入支付订单服务
    @DubboReference
    private IPaymentOrderService paymentOrderService;

    /**
     * 统一结算账单并发起支付宝支付
     *
     * @param request 请求参数，包括userId和billIds
     * @return 支付页面表单
     */
    @ApiOperation("统一结算账单并发起支付宝支付")
    @PostMapping(value = "/unified-settlement", produces = "text/html")
    public String unifiedSettlement(@RequestBody Map<String, Object> request) {
        try {
            Long userId = Long.valueOf(request.get("userId").toString());
            List<?> billIdsObj = (List<?>) request.get("billIds");
            Double totalAmount = Double.valueOf(request.get("totalAmount").toString());
            String subject = (String) request.get("subject");
            String body = (String) request.get("body");
            
            // 正确处理账单ID类型转换
            List<Long> billIds = billIdsObj.stream()
                .map(id -> {
                    if (id instanceof Long) {
                        return (Long) id;
                    } else if (id instanceof String) {
                        return Long.parseLong((String) id);
                    } else if (id instanceof Integer) {
                        return ((Integer) id).longValue();
                    }
                    return null;
                })
                .filter(id -> id != null)
                .collect(Collectors.toList());
            
            // 创建支付订单，获取系统生成的订单号
            String outTradeNo = paymentOrderService.createPaymentOrder(userId, totalAmount);
            log.info("为用户ID {} 创建支付订单，订单号: {}", userId, outTradeNo);
            
            // 格式化金额，确保为字符串且保留两位小数
            String formattedAmount = String.format("%.2f", totalAmount);
            
            String result = alipayConfig.pay(outTradeNo, formattedAmount, subject, body);
            return result;
        } catch (Exception e) {
            log.error("统一下单请求异常", e);
            return "统一下单请求失败";
        }
    }
}